package com.paobuji.aidebao.myapplication.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jaeger.library.StatusBarUtil;
import com.paobuji.aidebao.myapplication.R;
import com.paobuji.aidebao.myapplication.activity.BaseActivity;
import com.paobuji.aidebao.myapplication.adapter.ListRecyclerAdapter;
import com.paobuji.aidebao.myapplication.appinterface.GetInterfaceObjctListener;
import com.paobuji.aidebao.myapplication.bean.UserBeanResult;
import com.paobuji.aidebao.myapplication.tool.ACache;
import com.paobuji.aidebao.myapplication.tool.GetAppInfoUtil;
import com.paobuji.aidebao.myapplication.tool.ProgressDialog;
import com.paobuji.aidebao.myapplication.view.CircleImageView;
import com.paobuji.aidebao.myapplication.view.CustomTitlebar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

public class MyUserInfoSetActivity extends BaseActivity {

    @BindView(R.id.mainTitle)
    CustomTitlebar mainTitle;
    @BindView(R.id.myUserImage)
    CircleImageView myUserImage;
    @BindView(R.id.userName)
    TextView userName;
    @BindView(R.id.userBirthImg)
    ImageView userBirthImg;
    @BindView(R.id.userBirthPoint)
    ImageView userBirthPoint;
    @BindView(R.id.userBirthText)
    TextView userBirthText;
    @BindView(R.id.userBirthLayout)
    RelativeLayout userBirthLayout;
    @BindView(R.id.userWeightImg)
    ImageView userWeightImg;
    @BindView(R.id.userWeightPoint)
    ImageView userWeightPoint;
    @BindView(R.id.userWeightText)
    TextView userWeightText;
    @BindView(R.id.userWeightLayout)
    RelativeLayout userWeightLayout;
    @BindView(R.id.userHeightImg)
    ImageView userHeightImg;
    @BindView(R.id.userHeightPoint)
    ImageView userHeightPoint;
    @BindView(R.id.userHeightText)
    TextView userHeightText;
    @BindView(R.id.userHeightLayout)
    RelativeLayout userHeightLayout;
    @BindView(R.id.userBMIImg)
    ImageView userBMIImg;
    @BindView(R.id.userBMIPoint)
    ImageView userBMIPoint;
    @BindView(R.id.userBMIText)
    TextView userBMIText;
    @BindView(R.id.userBMILayout)
    RelativeLayout userBMILayout;
    @BindView(R.id.userHobbyImg)
    ImageView userHobbyImg;
    @BindView(R.id.userHobbyPoint)
    ImageView userHobbyPoint;
    @BindView(R.id.userHobbyText)
    TextView userHobbyText;
    @BindView(R.id.userHobbyLayout)
    RelativeLayout userHobbyLayout;
    @BindView(R.id.myImagwe)
    ImageView myImagwe;
    @BindView(R.id.offUser)
    Button offUser;


    private BottomSheetDialog mBottomSheetDialog;

    private ArrayList<String> mResultsPath = new ArrayList<>();

    private int year;
    private int month;
    private int day;
    String date;
    Context context;
    ACache aCache;

    UserBeanResult.DataBean.UserBean userBean;

    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_user_info_set);
        ButterKnife.bind(this);
        //设置全透明
        StatusBarUtil.setTransparent(this);
        context = getApplicationContext();
        aCache = ACache.get(context);
        progressDialog = new ProgressDialog(this);
        //userBean = new UserBeanResult.DataBean.UserBean();
        //在缓存中获取用户数据
        userBean = (UserBeanResult.DataBean.UserBean) aCache.getAsObject("userBean");
        //判断用户数据是否拿到，若没有的话从服务器拉取
        if (userBean == null) {
            myIntentTools.loginUserByIdentified(context, GetAppInfoUtil.getUniquePsuedoID());
            myIntentTools.setGetInterfaceObjctListener(new GetInterfaceObjctListener() {
                @Override
                public void getObjectDate(Object data) {
                    userBean = ((UserBeanResult) data).getData().getUser();
                    setViewText();
                }
            });
        } else {
            setViewText();
        }

        //权限监测
        CheckPerMission();

        //标题栏事件监测
        mainTitle.setAction(new CustomTitlebar.TitleBarOnClickListener() {
            @Override
            public void performAction(View view) {
                switch (view.getId()) {
                    case R.id.iv_left:
                        finish();
                        //Toast.makeText(MainActivity.this, "左边图片按钮", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.tv_left:
                        finish();
                        //Toast.makeText(MainActivity.this, "右边文字按钮", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.iv_right:
                        saveUserInfo();
                        //Toast.makeText(MainActivity.this, "右边文字按钮", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.tv_right:
                        saveUserInfo();
                        //Toast.makeText(MainActivity.this, "右边文字按钮", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
        initCatch();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    public void setViewText() {
        Glide.with(this)
                // .load(mResultsPath.get(0))
                .load(userBean.getUserImg())
                .asBitmap()
                .skipMemoryCache(false) //跳过内存缓存
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)     //缓存设置
                .priority(Priority.NORMAL)    //优先级  LOW     NORMAL      HIGH      IMMEDIATE
                .placeholder(R.mipmap.zhanwei)    //占位图
                .error(R.mipmap.zhanwei)
                .into(myUserImage);

        if("".equals(userBean.getUsername()) || userBean.getUsername() == null){
            userBean.setUsername("小强");
        }
        userName.setText(userBean.getUsername());
    }

    /*保存数据，保存到缓存中*/
    public void saveUserInfo() {
        progressDialog.showDialog();
        aCache.put("userBean", userBean);
        myIntentTools.UpdateUserInfoResult(context,userBean.getId(),userBean.getUsername(),
                userBean.getUsersex(),userBean.getBirth(),userBean.getUserhobby(),userBean.getUserImg(),
                userBean.getWeight(),userBean.getHeight());
        myIntentTools.setGetInterfaceObjctListener(new GetInterfaceObjctListener() {
            @Override
            public void getObjectDate(Object data) {
                if(((UserBeanResult)data).getCode() == 0){
                    progressDialog.cancelDialog();
                    finish();
                }else{
                    progressDialog.cancelDialog();
                }
            }
        });
    }

    /*获取数据*/
    public void initCatch() {
        userBirthText.setText(userBean.getBirth());
        userWeightText.setText(userBean.getWeight() + "kg");
        userHeightText.setText(userBean.getHeight() + "cm");
        userBMIText.setText("BMI");
        userHobbyText.setText(userBean.getUserhobby());
        userName.setText(userBean.getUsername());

        Glide.with(this)
                // .load(mResultsPath.get(0))
                .load(userBean.getUserImg())
                .asBitmap()
                .skipMemoryCache(true) //跳过内存缓存
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)     //缓存设置
                .priority(Priority.NORMAL)    //优先级  LOW     NORMAL      HIGH      IMMEDIATE
                .placeholder(R.mipmap.zhanwei)    //占位图
                .error(R.mipmap.zhanwei)
                .into(myUserImage);
    }

    @OnClick({R.id.myUserImage, R.id.userName, R.id.userBirthImg, R.id.userBirthPoint, R.id.userBirthText, R.id.userBirthLayout, R.id.userWeightImg, R.id.userWeightPoint, R.id.userWeightText, R.id.userWeightLayout, R.id.userHeightImg, R.id.userHeightPoint, R.id.userHeightText, R.id.userHeightLayout, R.id.userBMIImg, R.id.userBMIPoint, R.id.userBMIText, R.id.userBMILayout, R.id.userHobbyImg, R.id.userHobbyPoint, R.id.userHobbyText, R.id.userHobbyLayout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.myUserImage:
                getUrl(1);
                break;
            case R.id.userName:
                createBottomSheetDialog(20, 120, 5);
                break;
            case R.id.userBirthImg:
                createBottomSheetDialog(20, 120, 3);
                break;
            case R.id.userBirthPoint:
                createBottomSheetDialog(20, 120, 3);
                break;
            case R.id.userBirthText:
                createBottomSheetDialog(20, 120, 3);
                break;
            case R.id.userBirthLayout:
                createBottomSheetDialog(20, 120, 3);
                break;
            case R.id.userWeightImg:
                createBottomSheetDialog(20, 120, 1);
                break;
            case R.id.userWeightPoint:
                createBottomSheetDialog(20, 120, 1);
                break;
            case R.id.userWeightText:
                createBottomSheetDialog(20, 120, 1);
                break;
            case R.id.userWeightLayout:
                createBottomSheetDialog(20, 120, 1);
                break;
            case R.id.userHeightImg:
                createBottomSheetDialog(100, 220, 2);
                break;
            case R.id.userHeightPoint:
                createBottomSheetDialog(100, 220, 2);
                break;
            case R.id.userHeightText:
                createBottomSheetDialog(100, 220, 2);
                break;
            case R.id.userHeightLayout:
                createBottomSheetDialog(100, 220, 2);
                break;
            case R.id.userBMIImg:
                break;
            case R.id.userBMIPoint:
                break;
            case R.id.userBMIText:
                break;
            case R.id.userBMILayout:
                break;
            case R.id.userHobbyImg:
                createBottomSheetDialog(100, 220, 4);
                break;
            case R.id.userHobbyPoint:
                createBottomSheetDialog(100, 220, 4);
                break;
            case R.id.userHobbyText:
                createBottomSheetDialog(100, 220, 4);
                break;
            case R.id.userHobbyLayout:
                createBottomSheetDialog(100, 220, 4);
                break;
        }
    }


    /**
     * 获取本地图片路径
     * n 选择一张图片
     */
    private static final int REQUEST_CODE = 732;

    /**
     * 获取本地相册的路径
     *
     * @param n
     */
    public void getUrl(int n) {
        PhotoPickerIntent intentPhoto = new PhotoPickerIntent(MyUserInfoSetActivity.this);
        intentPhoto.setPhotoCount(n);
        intentPhoto.setShowCamera(true);
        startActivityForResult(intentPhoto, REQUEST_CODE);
    }

    /**
     * 图片路径地址的返回
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            if (data != null) {

                mResultsPath = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                userBean.setUserImg(mResultsPath.get(0));
                Log.i("图片", mResultsPath.get(0) + "------------");
                String imgUrl = mResultsPath.get(0);

                Glide.with(this)
                        .load(imgUrl).asBitmap()
                        .skipMemoryCache(true) //跳过内存缓存
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)     //缓存设置
                        .priority(Priority.NORMAL)    //优先级  LOW     NORMAL      HIGH      IMMEDIATE
                        .placeholder(R.mipmap.zhanwei)    //占位图
                        .error(R.mipmap.zhanwei)
                        .into(myUserImage);
            }
        }
    }

    /**
     * 底部滑动显示
     *
     * @param page
     * @param num
     * @param n
     */
    private void createBottomSheetDialog(final int page, int num, final int n) {
        //new 一个BottomSheetDialog对象
        mBottomSheetDialog = new BottomSheetDialog(this);
        //获取要添加到BottomSheetDialog中的布局view
        View view = createBottomSheetDialogContent(page, num, n);
        //将布局添加到BottomSheetDialog中
        mBottomSheetDialog.setContentView(view);

        //显示
        mBottomSheetDialog.show();
    }

    /**
     * @param page 起始值
     * @param num  结束值
     * @param n    1 体重 2身高    2生日   3 爱好
     * @return
     */
    private View createBottomSheetDialogContent(final int page, int num, final int n) {
        View view = null;
        switch (n) {
            case 1:
            case 2:
                view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_sheet, null, false);
                RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
                //Item宽或者高不会变，recyclerView的高改变
                recyclerView.setHasFixedSize(true);

                List<String> list = new ArrayList<>();
                for (int i = page; i <= num; i++) {
                    list.add(i + "");
                }
                //设置为竖向布局
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setSmoothScrollbarEnabled(true);
                recyclerView.setLayoutManager(linearLayoutManager);
                //设置适配器
                ListRecyclerAdapter adapter = new ListRecyclerAdapter(list);
                recyclerView.setAdapter(adapter);

                ListRecyclerAdapter.setOnItemClickListener(new ListRecyclerAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position, ArrayList talkList) {
                        if (mBottomSheetDialog.isShowing()) {
                            mBottomSheetDialog.dismiss();
                            //Toast.makeText(MyUserInfoSetActivity.this, (position + page) + "", Toast.LENGTH_SHORT).show();
                            if (n == 1) {
                                userBean.setWeight(position + page);
                                userWeightText.setText((position + page) + "kg");
                            } else if (n == 2) {
                                userBean.setHeight(position + page);
                                userHeightText.setText((position + page) + "cm");
                            }
                        } else {
                            mBottomSheetDialog.show();
                        }
                    }
                });
                break;
            case 3:
                view = LayoutInflater.from(this).inflate(R.layout.date_layout, null, false);
                TextView text = (TextView) view.findViewById(R.id.myOK);
                text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        userBean.setBirth(date);
                        userBirthText.setText(date);
                        mBottomSheetDialog.dismiss();
                    }
                });
                final DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker);
                //初始化DatePicker组件，初始化时指定监听器
                datePicker.init(1990, 01, 01, new DatePicker.OnDateChangedListener() {
                    @Override
                    public void onDateChanged(DatePicker arg0, int year, int month, int day) {
                        // 显示当前日期、时间
                        month = month + 1;
                        date = year + "-" + month + "-" + day;
                    }
                });
                break;
            case 4:
                view = LayoutInflater.from(this).inflate(R.layout.hobby_layout, null, false);
                final EditText myHobby = (EditText) view.findViewById(R.id.myHobby);
                TextView textOK = (TextView) view.findViewById(R.id.myOK);
                textOK.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (myHobby.getText().toString().trim() != null) {
                            userBean.setUserhobby(myHobby.getText().toString().trim());
                            userHobbyText.setText(myHobby.getText().toString().trim());
                        }
                        mBottomSheetDialog.dismiss();
                    }
                });
                break;
            case 5:
                view = LayoutInflater.from(this).inflate(R.layout.hobby_layout, null, false);
                final EditText myName = (EditText) view.findViewById(R.id.myHobby);
                TextView textYES = (TextView) view.findViewById(R.id.myOK);
                textYES.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (myName.getText().toString().trim() != null) {
                            userBean.setUsername(myName.getText().toString().trim());
                            userName.setText(myName.getText().toString().trim());
                        }
                        mBottomSheetDialog.dismiss();
                    }
                });
                break;

        }
        return view;
    }

    @OnClick(R.id.offUser)
    public void onClick() {
        aCache.put("userstate","false");
        startActivity(new Intent(getApplication(),LoginActivity.class));// 这个线程的作用3秒后就是进入到你的主界面
        MyUserInfoSetActivity.this.finish();
    }
}
